package com.sales.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.util.ISO8601DateFormat;
import com.sales.dao.CommissionDetailsDao;
import com.sales.entity.CommissionDetails;
import com.sales.excption.SalesException;
import com.sales.service.ProfileService;
import com.sales.util.GatewayUrlUtil;
import com.sales.util.OkHttpUtils;
import com.sales.vo.StoreVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by lihu on 2017/9/7.
 */
@Slf4j
@RestController
@RequestMapping(value = "/api/v1/sales", produces = "application/json;charset=utf-8")
public class StoresController {

    @Autowired
    ProfileService profileService;

    @Autowired
    GatewayUrlUtil gatewayUrlUtil;

    @Autowired
    CommissionDetailsDao commissionDetailsDao;

    /**
     * 获取店铺
     *
     * @param principal
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/my-stores")
    public ResponseEntity myStores(@PageableDefault(value = 10, sort = {"id"}, direction = Sort.Direction.DESC)
                                           Pageable pageable, Principal principal) {
        try {
            Map<String, Object> params = new HashMap<>();

            params.put("page", pageable.getPageNumber());
            params.put("size", pageable.getPageSize());
            String url = OkHttpUtils.getUrl(gatewayUrlUtil.getStords(), params);
            for (Sort.Order order : pageable.getSort()) {
                url += "&sort=" + order.getProperty() + "," + order.getDirection();
            }
            String result = null;
            List<String> codes = profileService.getReferralCodes(principal.getName());
            if (codes.size() > 0) {
                result = OkHttpUtils.post(url, JSONObject.toJSONString(codes));
            }
            StoreVo storeVo = null;
            DateFormat format = new ISO8601DateFormat();
            if (StringUtils.isNotBlank(result)) {
                JSONObject jsonObject = JSONObject.parseObject(result);
                storeVo = new StoreVo(jsonObject.getLong("totalPages"),
                        jsonObject.getLong("totalElements"));
                JSONArray jsonArray = jsonObject.getJSONArray("stores");
                Set<String> strings = new TreeSet<>();
                int j = jsonArray.size();
                List<String> storeIds = new ArrayList<>();
                for (int i = 0; i < j; i++) {
                    JSONObject object = jsonArray.getJSONObject(i);
                    Date time = format.parse(object.getString("lastRenewTime"));
                    //   Date time = object.getDate("lastRenewTime");
                    StoreVo.Store store = new StoreVo.Store(object.getString("id"),
                            object.getString("storeName"), time != null ? time : null,
                            object.getString("commissionOwner"), 0);
                    storeVo.getStores().add(store);
                    strings.add(store.getCommissionOwner());
                    storeIds.add(store.getId());

                }

                Map<String, Integer> map = new HashMap<>();
                if (storeIds.size() > 0) {
                    commissionDetailsDao.getCommissionAll(principal.getName(), storeIds).
                            forEach(e ->
                                    map.put(e[0].toString(), Integer.parseInt(e[1].toString()))
                            );
                }


                Map<String, String> profiles = profileService.getNameWithCode(strings);
                for (StoreVo.Store store : storeVo.getStores()) {
                    Integer amount = map.get(store.getId());
                    String owner = "";
                    if (profiles.get(store.getCommissionOwner()) != null) {
                        owner = profiles.get(store.getCommissionOwner());
                    }
                    store.setCommissionOwner(owner);
                    if (amount != null) {
                        store.setCommissionAmount(amount / 100d);
                    }
                }
            }
            return new ResponseEntity(storeVo, HttpStatus.OK);
        } catch (SalesException ex) {
            log.error("myStores is error=>principal:{}", principal, ex);
            return new ResponseEntity(ex.getMessage(), HttpStatus.BAD_REQUEST);
        } catch (Exception ex) {
            log.error("myStores is error=>principal:{}", principal, ex);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }

    }

}
